<?php
function getUser($fbid){
	$db = new db();
	$query = "SELECT * FROM Pengguna WHERE idFB = '$fbid'";
	$ret = $db->query($query);
	return $ret[0];
}

function getNamaToko($fbid){
	$db = new db();
	$query = "SELECT `nama-toko` FROM Pengguna WHERE idFB = '$fbid'";
	$ret = $db->query($query);
	return $ret[0]['nama-toko'];
}

function getUserId($id){
	$db = new db();
	$query = "SELECT * FROM Pengguna WHERE idPengguna = '$id'";
	$ret = $db->query($query);
	return $ret[0];
}

function getListBarang($idpenjual){
	$db = new db();
	$query = "SELECT * FROM Barang WHERE idPenjual = $idpenjual";
	$ret = $db->query($query);
	return $ret;
}

function getListAlamat($idpembeli){
	$db = new db();
	$query = "SELECT * FROM Alamat WHERE idPembeli = $idpembeli";
	$ret = $db->query($query);
	return $ret;
}

function getBarang($id){
	$db = new db();
	$query = "SELECT * FROM Barang WHERE idBarang = '$id'";
	$ret = $db->query($query);
	return $ret[0];
}

function getBarangSlug($slug){
	$db = new db();
	$query = "SELECT * FROM Barang WHERE `slug-nama` = '$slug'";
	$ret = $db->query($query);
	return $ret[0];
}

function getTokoSlug($slug){
	$db = new db();
	$query = "SELECT * FROM Pengguna WHERE `slug_nama-toko` = '$slug'";
	$ret = $db->query($query);
	return $ret[0];
}

function getAlamat($id){
	$db = new db();
	$query = "SELECT * FROM Alamat WHERE idAlamat = '$id'";
	$ret = $db->query($query);
	return $ret[0];
}

function getArtikel($id){
	$db = new db();
	$query = "SELECT a.tanggal,a.judul,a.isi,a.tag,p.nama,a.idArtikel,a.`slug-judul`,a.type,a.idReview,p.idFB,b.nama as nama_barang,b.idBarang
				FROM `Artikel` a
				INNER JOIN Pengguna p ON a.idPublisher = p.idPengguna
				INNER JOIN Barang b ON a.idReview = b.idBarang
				WHERE a.idArtikel = '$id'";
	$ret = $db->query($query);
	return $ret[0];
}

function getPesananTrans($idtrans){
	$db = new db();
	
}

function getTrans($id){
	$db = new db();
	$query = "SELECT * FROM Transaksi WHERE idTransaksi = '$id'";
	$ret = $db->query($query);
	return $ret[0];
}

function explodeTrim($delim,$text){
	$tags = explode($delim,$text);
	$ret = array();
	foreach ($tags as $tag){
		$tmp = trim($tag);
		array_push($ret,$tmp);
	}
	return $ret;
}

function amankan($str) {
	// experimental
	if (get_magic_quotes_gpc()) {
		return $str;
	} else {
		if (function_exists('addslashes')) {
			return addslashes($str);
		} else {
			return mysql_real_escape_string($str);
		}
	}
}

function getKategori($no){
	switch ($no){
		case 1:
			$ret = "Fashion";
			break;
		case ($no>1 && $no<5):
			$ret = "Alat Elektronik";
			break;
		case 5:
			$ret = "Kesehatan & Kecantikan";
			break;
		case ($no>5 && $no<9):
			$ret = "Perlengkapan";
			break;
		case ($no>8 && $no<13):
			$ret = "Kesenian & Kerajinan Tangan";
			break;
		case 13:
			$ret = "Hobi & Olahraga";
			break;
		case 14:
			$ret = "Kebun & Taman";
			break;
		case 15:
			$ret = "Makanan";
			break;
		default:
			$ret = "Lain-lain";
			break;
	}
	return $ret;
}

function getMarket($no){
	switch ($no){
		case 1:
			$ret = "fashion";
			break;
		case ($no>1 && $no<5):
			$ret = "elektronik";
			break;
		case 5:
			$ret = "kesehatan";
			break;
		case ($no>5 && $no<9):
			$ret = "perlengkapan";
			break;
		case ($no>8 && $no<13):
			$ret = "seni";
			break;
		case 13:
			$ret = "hobi";
			break;
		case 14:
			$ret = "kebun";
			break;
		case 15:
			$ret = "makanan";
			break;
		default:
			$ret = "lain";
			break;
	}
	return $ret;
}

function sendEmail($email,$pesan,$subject,$from_name){
	$mail = new PHPMailer();  // create a new object
	$mail->IsSMTP(); // enable SMTP
	$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
	$mail->SMTPAuth = true;  // authentication enabled
	$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
	$mail->Host = 'smtp.gmail.com';
	$mail->Port = 465;
	$from = "realita.umkm@gmail.com";
	$mail->Username = $from;  
	$mail->Password = "r34l1taumkm";
	//$mail->Host = "mail.desatarumajaya.com";
	//$mail->Port = 25;
	//$mail->Username = "me@ans4175.com"; // SMTP username
	//$mail->Password = "anshorimail"; // SMTP password 
	$mail->SetFrom($from, $from_name);  
	$mail->Subject  = $subject;
	$mail->Body = $pesan;
	$mail->AddAddress($email);
	if(!$mail->Send()) {
		$error = 'Mail error: '.$mail->ErrorInfo; 
		//return false;
	} else {
		$error = 'Message sent!';
		//return true;
	}
	echo $error;
}

function sendSMS($nomor,$pesan){
	$ukey = "nbga3t";
	$pkey = "t3agbn";
	$url = 'http://zenziva.com/apps/smsapi.php?userkey='.$ukey.'&passkey='.$pkey.'&nohp='.$nomor.'&pesan='.urlencode($pesan);
	$curlHandle = curl_init();
	curl_setopt($curlHandle, CURLOPT_URL, $url);
	//curl_setopt($curlHandle, CURLOPT_HEADER, 0);
	curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlHandle, CURLOPT_USERAGENT, 'Codular Sample cURL Request');
	curl_setopt($curlHandle, CURLOPT_TIMEOUT,30);
	$results = curl_exec($curlHandle);
	curl_close($curlHandle);
}

function no_index() {
	return '<meta name="robots" content="noindex,nofollow" />'.NL;
}

function int_to_rp($int) {
	$int = str_split((string)$int);
	$i = 0;
	$retval = "";
	for ($j = count($int) - 1; $j >= 0; $j--) {
		if ($i == 3) {
			$retval = $int[$j].".".$retval;
			$i = 1;
		} else {
			$retval = $int[$j].$retval;
			$i++;
		}		
	}
	$retval = "Rp ".$retval;
	return $retval;
}

function rp_to_int($rp) {
	$rp = explode(" ",$rp);
	$rp = $rp[1];
	$rp = explode(".",$rp);
	$retval = "";
	foreach ($rp as $tiga) {
		$retval .= $tiga;
	}
	return intval($retval);
}

function slugging($string) {
	$nstring = preg_replace("/[^a-zA-Z0-9]/","-",strtolower($string));
	return $nstring;
}

function paginasi($query,$ulink,$limit=5){
	if (isset($_GET['pg'])){
		$page=$_GET['pg'];
	}else{
		$page=1;
	}
	$db = new db();
	$start=($page-1)*$limit;
	$qres = $db->query($query." LIMIT $start,$limit");	//--->isinya
	$res = $db->query($query);	//--->isinya
	
	$totpost=$db->rowCount();
	//echo $totpost;
	if ($totpost>0){											
		$adjacents = 2;	//mainin hide-hide
		$totpage=($totpost/$limit);
		if ($totpost<=$limit) $totpage=1;
		
		//$page=1;	//page now
		$prev = $page - 1;							//previous page is page - 1
		$next = $page + 1;							//next page is page + 1
		$lastpage = ceil($totpost/$limit);		//lastpage is = total pages / items per page, rounded up.
		$lpm1 = $lastpage - 1;						//last page minus 1
		
		$uprev = $ulink."&pg=".$prev;
		$unext = $ulink."&pg=".$next;
		$ulast = $ulink."&pg=".$lastpage;
		$ulm1 = $ulink."&pg=".$lpm1;
		
		$pagination = "<div class='row' id='konten-patas'><div class=\"large-8 small-6 columns\">\n";
			if($lastpage > 1)	//cek lebih dari satu halaman
			{	
				$pagination .= "<ul class=\"pagination\">\n";
				//previous button
				if ($page > 1) 
					$pagination.= "<li><a href=\"$uprev\">&laquo;</a></li>\n";
				else
					$pagination.= "<li class=\"arrow unavailable\"><a href=\"#\">&laquo;</a></li>\n";	
				
				//pages	
				if ($lastpage <= 3 + ($adjacents * 2))	//not enough pages to bother breaking it up
				{	
					for ($counter = 1; $counter <= $lastpage; $counter++)
					{
						if ($counter == $page)
							$pagination.= "<li class=\"current\"><a href=\"#\">$counter</a></li>\n";
						else{
							$ucount = $ulink."&pg=".$counter;
							$pagination.= "<li><a href=\"$ucount\">$counter</a></li>\n";
						}
					}
				}
				else if($lastpage > 3 + ($adjacents * 2))	//enough pages to hide some
				{
					//close to beginning; only hide later pages
					if($page < 3 + ($adjacents * 2))		
					{
						for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
						{
							if ($counter == $page)
								$pagination.= "<li class=\"current\"><a href=\"#\">$counter</a></li>\n";
							else{
								$ucount = $ulink."&pg=".$counter;
								$pagination.= "<li><a href=\"$ucount\">$counter</a></li>\n";
							}
						}
						$pagination.= "...";
						$pagination.= "<li><a href=\"$ulm1\">$lpm1</a></li>\n";
						$pagination.= "<li><a href=\"$ulast\">$lastpage</a></li>\n";
					}
					//in middle; hide some front and some back
					else if($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
					{
						$u1 = $ulink."&pg=1";
						$u2 = $ulink."&pg=2";
						$pagination.= "<li><a href=\"$u1\">1</a></li>\n";
						$pagination.= "<li><a href=\"$u2\">2</a</a></li>\n";
						$pagination.= "...";
						for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
						{
							if ($counter == $page)
								$pagination.= "<li class=\"current\"><a href=\"#\">$counter</a></li>\n";
							else{
								$ucount = $ulink."&pg=".$counter;
								$pagination.= "<li><a href=\"$ucount\">$counter</a></li>\n";
							}
						}
						$pagination.= "<li>...</li>";
						$pagination.= "<li><a href=\"$ulm1\">$lpm1</a></li>\n";
						$pagination.= "<li><a href=\"$ulast\">$lastpage</a></li>\n";		
					}
					//close to end; only hide early pages
					else
					{
						$u1 = $ulink."&pg=1";
						$u2 = $ulink."&pg=2";
						$pagination.= "<li><a href=\"$u1\">1</a></li>\n";
						$pagination.= "<li><a href=\"$u2\">2</a</a></li>\n";
						$pagination.= "...";
						for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
						{
							if ($counter == $page)
								$pagination.= "<li class=\"current\"><a href=\"#\">$counter</a></li>\n";
							else{
								$ucount = $ulink."&pg=".$counter;
								$pagination.= "<li><a href=\"$ucount\">$counter</a></li>\n";	
							}				
						}
					}
				}
				
				//next button
				if ($page < $counter - 1) 
					$pagination.= "<li><a href=\"$unext\">&raquo;</a></li>\n";
				else
					$pagination.= "<li class=\"arrow unavailable\"><a href=\"#\">&raquo;</a></li>\n";
				$pagination.= "</ul>\n";		
			}
			//echo $pagination;
		$pagination .= "</div></div>\n";
	}
	$result['sql'] = $qres;
	$result['page'] = $pagination;
	return $result;
}

function convDate($dtime){
	$mtime = strtotime($dtime);
	$tgl = date("d/m/Y",$mtime);
	return $tgl;
}

function get_city($query,$isorigin = TRUE) {
	$rest = new REST_Ongkir(array(
		'server' => 'http://api.ongkir.info/'
	));
	//ganti API-Key dibawah ini sesuai dengan API Key yang anda peroleh setalah mendaftar di ongkir.info
	$type = ($isorigin) ? 'origin' : 'destination';
	$result = $rest->post('city/list', array(
		'query' => $query,
		'type' => $type,
		'courier' => 'jne',
		'API-Key' => '6837b700c38ea8484cac8df18fe342cf',
		'format' => 'json'
	));

	try {
		//return $result;
		$status = $result->status;
		// Handling the data
		if ($status->code == 0){
			return $cities = $result->cities;
		}else{
			//echo 'Tidak ditemukan kota yang diawali '.$query;
			return array();
		}
	}catch (Exception $e){
		echo 'Processing error.';
	}
}

function get_cost($from,$to,$weight){
	$rest = new REST_Ongkir(array(
		'server' => 'http://api.ongkir.info/'
	));
//ganti API-Key dibawah ini sesuai dengan API Key yang anda peroleh setalah mendaftar di ongkir.info
	$result = $rest->post('cost/find', array(
		'from' => $from,
		'to' => $to,
		'weight' => $weight,
		'courier' => 'jne',
		'API-Key' =>'6837b700c38ea8484cac8df18fe342cf',
		'format' => 'json'
	));
	
	try{
		//return $result;
		$status = $result->status;
		// Handling the data
		if ($status->code == 0){
			$prices = $result->price;
			foreach ($prices as $price){
				if ($price->service_code == 'oke') return $price->value;
			}
		}else{
			echo 'Tidak ditemukan jalur pengiriman';
			return 25000;
		}
	}catch (Exception $e){
		echo 'Processing error.';
	}
}
